<?php

namespace KyleWechat\MiniProgram;

use GuzzleHttp\Exception\GuzzleException;
use KyleWechat\App;
use KyleWechat\Exception\InvalidParamException;

class MiniProgram extends App
{
    /**
     * get openid
     * @throws GuzzleException
     */
    public function openid($code)
    {
        if (!$code) {
            throw new InvalidParamException('invalid code','MiniProgram');
        }
        $res = $this->app->config->httpClient->get($this->app->config::API['miniProgram']['openid'],[
            'appid' => $this->app->config->getAppid(),
            'secret' => $this->app->config->getSecret(),
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ]);
        return json_decode($res, true);
    }

    /**
     * 解密获取手机号
     * @param $encryptedData
     * @param $sessionKey
     * @param $iv
     * @return int[]|mixed
     */
    public function mobile($encryptedData, $sessionKey, $iv)
    {
        if (strlen($sessionKey) != 24) {
            return ['errCode' => -41001];
        }
        $aesKey = base64_decode($sessionKey);

        if (strlen($iv) != 24) {
            return ['errCode' => -41002];
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode( $result );
        if( $dataObj  == NULL )
        {
            return ['errCode' => -41003];
        }
        if( $dataObj->watermark->appid != $this->app->config->getAppid() )
        {
            return ['errCode' => -41004];
        }
        return json_decode($result,true);
    }

    /**
     * 生成小程序码
     * @param $path
     * @param string $env_version
     * @return string
     * @throws GuzzleException
     */
    public function getMiniProgramQrCodeUnLimit($path, string $env_version = 'release'): string
    {
        $info = parse_url($path);
        $param = [
            'page'  => $info['path'],
            'is_hyaline' => true,
            'env_version' => $env_version
        ];
        $query = $info['query']??'';
        if ($query) list(,$param['scene']) = explode('=',$query);
        return $this->app->config->httpClient
            ->sendJson($this->app->config::API['miniProgram']['qrcode'].$this->getAccessToken(),$param);
    }

    private function getAccessToken()
    {
        $res = $this->app->config->httpClient
            ->get($this->app->config::API['access_token'],[
                'grant_type' => 'client_credential',
                'appid' => $this->app->config->getAppid(),
                'secret' => $this->app->config->getSecret()
            ]);
        $res = json_decode($res,true);
        return $res['access_token'];
    }
}